<template>
  <view class="visit">
    <globalNavBar title="添加预约人"/>
    <view class="container  flex_wrap">
	<view class="flex flex_column view_time " >
		<view class="appointmen_time">
			参观时间: {{appointment_datetime.format}}
		</view>
	</view>	
	<view class=" flex flex_column appointment_container">
		<view class="appointment_title">预约人</view>
		<view class="appointment_list_container">
			<view class="appointment_container_border " v-for="item in appointment_list" :key="item.id">
				<view class="flex appointment_list">
					<view class="flex flex_column">
						<view class="mt-10">姓名：{{item.username}}</view>
						<view class="mt-10">手机号：{{item.mobile}}</view>
						<view class="mt-10">携带儿童：{{item.child_count}}</view>
					</view>
					<view>
						<button @click="deleteAppointmentPeople(item.id)" size="mini">删除</button>
					</view>
				</view>
			</view>
		</view>

		
		<view class="add_appointment">
			<button @click="addAppointment">添加预约人最多可添加{{max_appointment_count}}人</button>
		</view>
	</view>
	<view class="flex" style="justify-content: center;">
		<view style="width: 90%;margin-top: 100rpx;">
			<button @click="goAppointment">确认预约</button>
		</view>
	</view>
		
	<uv-popup ref="popup"  mode="center">
		<view style="width: 750rpx; height: min-height:400rpx; height: 1000rpx; overflow-y: scroll;">
			<view class="flex flex_column appuser_container">
				<view class="flex" style="justify-content: space-evenly; align-items: center; width: 100%;">
					<view>填写预约人信息</view>
					<view ><button size="mini" @click="openAppointmentManager">查看预约人列表</button></view>
				</view>
				<view class="flex flex_wrap has_appuser_list">
					<view @click="useHistoryInfo(item.id)" class="user " :class="viewuser_info.id == item.id ? 'userSelected' : ''" v-for="item in viewuser_list" :key="item.id">{{item.username}}</view>
				</view>
				<view>
					<uv-form labelPosition="left" :model="viewuser_info"  ref="form">
						<uv-form-item label="姓名" labelWidth="140rpx" prop="viewuser_info.username" borderBottom required>
						  <uv-input v-model="viewuser_info.username" border="none" placeholder="请输入姓名"/>
						</uv-form-item>
						<uv-form-item label="手机号" labelWidth="140rpx" prop="viewuser_info.username" borderBottom required>
						  <uv-input v-model="viewuser_info.mobile" border="mobile" placeholder="请输入手机号"/>
						</uv-form-item>
						<uv-form-item label="儿童数量" labelWidth="140rpx" prop="viewuser_info.child_count" borderBottom required>
						  <uv-radio-group v-model="viewuser_info.child_count" placement="row">
						    <uv-radio :customStyle="{padding: '0 10px'}" name="9999" label="无"/>
							<uv-radio :customStyle="{padding: '0 10px'}" name="1" label="1"/>
							<uv-radio :customStyle="{padding: '0 10px'}" name="2" label="2" />
						  </uv-radio-group>
						</uv-form-item>
						<uv-form-item v-if="idnum_show != 1" label="身份证" labelWidth="140rpx" prop="viewuser_info.idnum" borderBottom required>
						  <uv-input v-model="viewuser_info.idnum" border="idnum" placeholder="请输入身份证"/>
						</uv-form-item>
						<uv-form-item label="脸部照片" prop="viewuser_info.mobile.face_image" labelWidth="200rpx" borderBottom
						              @click="uploadFaceImage" >
						  <uv-upload
						    :fileList="uploadFileList"
						    name="1"
							:maxCount="1"
							:previewFullImage="true"
									@afterRead="afterRead" 
									@delete="deletePic" 
						  />
						</uv-form-item>
					</uv-form>
				</view>
				<view>
					<view style="width: 400rpx; margin-top: 50rpx;">
						<button @click="sureAddAppointment">确认</button>
					</view>
				</view>
			</view>
		</view>
	</uv-popup>
	</view>
  </view>
</template>

<script>
	import http from '@/utils/request.js'
export default {
  data() {
    return {
		uploadFileList:[],
		appointment_list:[

		],
		viewuser_list:[
	
		],
		viewuser_info:{
			username:'',
			mobile:'',
			face_image:'',
			child_count:0,
			id:'',
			idnum:''
		},
		appointment_datetime : {
			format:'',
			date:'',
			artype:'',
		},
		max_appointment_count : 4,
		idnum_show:1,
    };
  },
  onLoad(options) {
	this.appointment_datetime.date = options.appointment_date
	this.appointment_datetime.artype = options.artype
	this.appointment_datetime.format = options.appointment_date + ' ' + options.artype_format
	this.getConfig();
	this.getViewuserList();
  },
  onShow() {
  	this.getViewuserList();
  },
  methods: {
	  // 
	  openAppointmentManager(){
		uni.navigateTo({
			url:'/pages/booking/appointment_manager'
		})  
	  },
	  // 删除预约人
	deleteAppointmentPeople(id){
		for(let i = 0; i < this.appointment_list.length;i++){
			if(this.appointment_list[i].id == id){
				console.log(i)
				this.appointment_list.splice(i, 1)
				break;
			}
		}
	},
	// 使用之前的预约人信息
	useHistoryInfo(id){
		for(let i = 0; i < this.viewuser_list.length;i++){
			if(this.viewuser_list[i].id == id){
				let info = this.viewuser_list[i];
				this.viewuser_info.username = info.username;
				this.viewuser_info.mobile = info.mobile;
				this.viewuser_info.id = info.id;
				this.viewuser_info.idnum = info.idnum
				console.log(info);
				if(info.face_image){
					if(this.uploadFileList[0]){
						this.uploadFileList[0].url = http.common.baseUri+info.face_image
					}else{
						this.uploadFileList.push({url:http.common.baseUri+info.face_image})
					}
				}else{
					this.uploadFileList.shift()
				}
				break;
			}
		}
	},
	// 添加预约人
   addAppointment(){
	   if(this.appointment_list.length >= this.max_appointment_count){
		   let errMsg = '最多可添加'+this.max_appointment_count+'人'
		   uni.showToast({
				title: errMsg
		   })
		   return false;
	   }
	   this.viewuser_info.username = '';
	    this.viewuser_info.mobile = '';
		 this.viewuser_info.child_count = 0;
		  this.viewuser_info.id = '';
		   this.viewuser_info.face_image = '';
		this.viewuser_info.idnum = '';		   
	   this.$refs.popup.open();
   },
   isJson(str){
   	if (typeof str === "string") {
   	        try {
   	          var obj = JSON.parse(str);
   	          if (obj && typeof obj === "object") {
   	            return true;
   	          } else {
   	            return false;
   	          }
   	        } catch (e) {
   	          console.log("$isJSON error：", e);
   	          return false;
   	        }
   	      } else {
   	        return false;
   	      }
   },
   // 创建用户关联的预约人
   sureAddAppointment(){
	if(this.uploadFileList[0]){
		let imageJson = this.uploadFileList[0].url
		if(this.isJson(imageJson)){
			this.viewuser_info['face_image'] = JSON.parse(imageJson).data.url;	  
		}else{
			this.viewuser_info['face_image'] = this.uploadFileList[0].url.replace(http.common.baseUri,'');
		}  
	}  
	if(!this.viewuser_info['mobile']){
		uni.showToast({
			title: '请填写手机号'
		})
		return false;
	}
	if(!this.viewuser_info['username']){
		uni.showToast({
			title: '请填写姓名'
		})
		return false;
	}
	if(!this.viewuser_info['child_count']){
		uni.showToast({
			title: '请填选择儿童人数'
		})
		return false;
	}
	
	http.post('api/user/update_appointment_people',this.viewuser_info).then((data)=>{
		if(data.code == 1 && data.data){
			this.viewuser_info.id = data.data;
			let hasSet = false;
			let hasSet2 = false;
		for(let i = 0; i < this.appointment_list.length;i++){
			if(this.appointment_list[i].id == this.viewuser_info.id){
				hasSet = true;
				this.appointment_list[i].username = this.viewuser_info.username
				this.appointment_list[i].mobile = this.viewuser_info.mobile
				this.appointment_list[i].child_count =this.viewuser_info.child_count == 9999 ? '无':this.viewuser_info.child_count
				break;
			}

		}
		for(let i = 0; i < this.viewuser_list.length;i++){
			if(this.viewuser_list[i].id == this.viewuser_info.id){
				hasSet2 = true;
				this.viewuser_list[i].username = this.viewuser_info.username
				this.viewuser_list[i].mobile = this.viewuser_info.mobile
				this.viewuser_list[i].idnum = this.viewuser_info.idnum
				this.viewuser_list[i].child_count =this.viewuser_info.child_count == 9999 ? '无':this.viewuser_info.child_count
				break;
			}
		
		}
		if(!hasSet){
			this.appointment_list.push({
				'id':this.viewuser_info.id,
				'username' : this.viewuser_info.username,
				'mobile' : this.viewuser_info.mobile,
				'idnum':this.viewuser_info.idnum,
				'child_count':this.viewuser_info.child_count == 9999 ? '无':this.viewuser_info.child_count
			})

		}
		if(!hasSet2){
			this.viewuser_list.push({
				'id':this.viewuser_info.id,
				'username' : this.viewuser_info.username,
				'mobile' : this.viewuser_info.mobile,
				'idnum':this.viewuser_info.idnum,
				'child_count':this.viewuser_info.child_count == 9999 ? '无':this.viewuser_info.child_count
			})
		}

			this.$refs.popup.close()
		}else{
			uni.showToast({
				title: '添加失败'
			})
		}
	})
   },
   goAppointment(){
	http.post('api/yuyue/yuyue_submit',
	{list:this.appointment_list,
	'yuyue_date':this.appointment_datetime.date,
	'artype':this.appointment_datetime.artype,
	
	}).then(res=>{
		if(res.code == 1){
			uni.showToast({
				title: '添加成功'
			})
			setTimeout(()=>{
				uni.navigateTo({
					url:'/pages/booking/mylist'
				})
			},2000)
		}
	}) 
   },
	getConfig(){
		http.get('api/user/max_appointment_count',{}).then((data)=>{
			this.max_appointment_count = data.data.max_count;
			this.idnum_show = data.data.idnum_show;
		})
	},
	getViewuserList(){
		http.get('api/user/appointment_manager_list',{}).then((data)=>{
			this.viewuser_list = data.data;
		})
	},
	
	deletePic(event) {
		this[`uploadFileList`].splice(event.index, 1)
	},
	// 新增图片
	async afterRead(event) {
		// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListLen = this[`uploadFileList`].length
		lists.map((item) => {
			this[`uploadFileList`].push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		for (let i = 0; i < lists.length; i++) {
			const result = await this.uploadFilePromise(lists[i].url)
			let item = this[`uploadFileList`][fileListLen]
			this[`uploadFileList`].splice(fileListLen, 1, Object.assign(item, {
				status: 'success',
				message: '',
				url: result
			}))
			fileListLen++
		}
	},
	uploadFilePromise(url) {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: http.common.baseUrl+'api/common/upload', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				 header: {
					'token': uni.getStorageSync('token') // 设置认证token
				  },
				success: (res) => {
					setTimeout(() => {
						resolve(res.data)
					}, 1000)
				}
			});
		})
	},
	
	
  }
}
</script>

<style lang="scss" scoped>
	
	.flex {
		display: flex;
	}
	.flex_center {
		display: flex;
		justify-content: center;
	}
	.flex_wrap {
		flex-wrap: wrap;
	}
	.flex_column {
		flex-direction: column;
	}
	.mt-10 {
		margin-top: 10rpx;
	}
	.container {
	}
	.view_time {
		width: 100%;
		padding-left: 50rpx;
		height: 150rpx;
		line-height: 150rpx;
		background: #eee;
		.appointmen_time {	
			color: fuchsia;
		}
		margin-bottom: 20rpx;
	}
	
	.appointment_container {
		padding: 20rpx 50rpx;
		background:  #eee;
		.appointment_title {
			align-self: center;
		}
		.appointment_list_container {
			min-height: 300rpx;
		}
		.appointment_list {
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			font-size: 24rpx;
		}
		.add_appointment {
			margin-top: 20rpx;
		}
	}
	.appointment_container_border {
		border: 1px solid fuchsia;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}
	
	.appuser_container {
		align-items: center;
		padding-top: 30rpx;
		
		.has_appuser_list {
			margin: 20rpx 0;
			
			.user {
				border: 1px solid #eee;
				padding: 10rpx;
				margin: 0 10rpx;
			}
			.userSelected {
				background-color: skyblue;
				color: #fff;
			}
		}
	}

	
</style>
